/*******************************************************************************
 * Copyright 2009 Dop Sun
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
/**
 * Place holder for copyright, needs to be replaced before release.
 */
package com.softao.ming.gde.internal.core.export;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.pde.core.plugin.IPluginModelBase;
import org.eclipse.pde.core.plugin.PluginRegistry;
import org.eclipse.pde.internal.core.exports.FeatureExportInfo;
import org.eclipse.pde.internal.core.ibundle.IBundlePluginModel;
import org.eclipse.pde.internal.ui.build.PluginExportJob;

import com.softao.ming.gde.internal.core.natures.GdePluginFile;

/**
 * 
 */
@SuppressWarnings("restriction")
public class PluginExporter {
	
	/**
	 * @param destinationDirectory 
	 * @param monitor 
	 * @throws CoreException 
	 */
	public final void export(String destinationDirectory, IProgressMonitor monitor) throws CoreException {
		FeatureExportInfo exportInfo = new FeatureExportInfo();
		exportInfo.toDirectory = true;
		exportInfo.useJarFormat = true;
		exportInfo.exportSource = false;
		exportInfo.exportMetadata = false;
		exportInfo.destinationDirectory = destinationDirectory;
		exportInfo.zipFileName = null;
		exportInfo.items = getModules();
		
		PluginExportJob job = new PluginExportJob(exportInfo);
		job.schedule();
		try {
			job.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private IBundlePluginModel[] getModules() {
		List<IBundlePluginModel> result = new ArrayList<IBundlePluginModel>();
		for (IPluginModelBase plugin : PluginRegistry.getActiveModels()) {
			String installLocation = plugin.getInstallLocation();
			File file = new File(installLocation);
			
			if (!file.isFile()) {
				File gwtPluginFile = new File(file, GdePluginFile.FILE_NAME);
				if (!gwtPluginFile.exists()) {
					continue;
				}

				IResource resource = plugin.getUnderlyingResource();
				if (resource != null) {
					result.add((IBundlePluginModel)plugin);
				}
			}
		}
		return result.toArray(new IBundlePluginModel[result.size()]);
	}
}
